package com.qcb.expresswrapping.controller;

import cn.hutool.core.map.MapUtil;
import com.qcb.expresswrapping.common.Result;
import com.qcb.expresswrapping.entity.UserInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: QCB
 * @create: 2022-03-10-19:38
 * To change this template use File | Settings | File and Code Templates.
 */
@RestController
@RequestMapping("/pc/userinfo")
public class PcUserInfoController extends BaseController{

    @GetMapping("/info")
    @PreAuthorize("hasAuthority('pc:user:info')")
    public Result info(Principal principal) {
        UserInfo userInfo = pcUserInfoService.getById(sysUserService.getByUsername(principal.getName()).getId());
        Assert.notNull(userInfo, "找不到该用户信息");
        return Result.success(userInfo);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('pc:user:save')")
    public Result save(@Validated @RequestBody UserInfo userInfo, Principal principal) {
        userInfo.setAccountId(sysUserService.getByUsername(principal.getName()).getId());
        pcUserInfoService.save(userInfo);
        return Result.success(userInfo);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('pc:user:update')")
    public Result update(@Validated @RequestBody UserInfo userInfo, Principal principal) {
        userInfo.setAccountId(sysUserService.getByUsername(principal.getName()).getId());
        pcUserInfoService.updateById(userInfo);
        return Result.success(userInfo);
    }

    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('pc:user:delete')")
    public Result delete(@PathVariable("id") long id) {
        pcUserInfoService.removeById(id);
        return Result.success(MapUtil.builder()
        .put("msg", "用户信息删除成功")
        .build());
    }

}
